<template>
	<view class="preview">
		<!-- 轮播图 -->
		<swiper circular :current="currentIndex" @change="currentChange">
			<swiper-item v-for="(item, index) in classList" :key="item.classid">
				<image :src="item.picurl" mode="aspectFill" @click="maskChange" v-if="lazyImg.includes(index)"></image>
			</swiper-item>
		</swiper>
		<!-- 遮罩层 -->
		<view class="mask" v-if="maskState">
			<!-- 返回按钮 -->
			<view class="goBack" :style="{ top: getStatusBarHeight() + 'px' }" @click="goBack">
				<uni-icons type="back" color="#fff" size="20" />
			</view>
			<view class="count">
				{{ currentIndex + 1 }} / {{ classList.length }}
			</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>

			</view>
			<view class="footer">
				<view class="box" @click="ClickInfo">
					<uni-icons type="info" size="23"></uni-icons>
					<view class="text">
						信息
					</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="23"></uni-icons>
					<view class="text">
						分数
					</view>
				</view>
				<view class="box" @click="download">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">
						下载
					</view>
				</view>
			</view>
		</view>

		<uni-popup ref="infoPopup">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="closePop">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y="true">
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID: </view>
							<text selectable class="value"> {{ imgInfo._id }}</text>
						</view>
						<!-- <view class="row">
							<view class="label">分类: </view>
							<text selectable class="value class">明星美女</text>
						</view> -->
						<view class="row">
							<view class="label">发布者: </view>
							<text select able class="value"> {{ imgInfo.nickname }}</text>
						</view>
						<view class="row">
							<view class="label">评分: </view>
							<view class="value roteBox">
								<uni-rate :value="imgInfo.score" size="16" />
								<text class="score"> {{ imgInfo.score }}</text>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要: </view>
							<text selectable class="value"> {{ imgInfo.description }}</text>
						</view>
						<view class="row">
							<view class="label">标签: </view>
							<view class="value tabs">
								<view class="tab" v-for="item in imgInfo.tabs" :key="item">
									{{ item }}
								</view>
							</view>

						</view>
						<view class="copyright">
							声明:本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸维护您的权益。
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>


		<uni-popup ref="scorePop" :is-mask-click="false">
			<view class="scorePop">
				<view class="popHeader">

					<view></view>
					<view class="title">{{ isSocre ? '评分过了' : '壁纸评分' }}</view>
					<view class="close" @click="closeScorePop">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<view class="content">
					<uni-rate v-model="userScore" allow-half :disabled="isSocre" disabled-color="#ffca3e"></uni-rate>
					<text class="text">{{ userScore }}分</text>
				</view>
				<view class="footer">
					<button :disabled="!userScore || isSocre" type="default" size="mini" plain
						@click="submitScore">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup>
import { ref } from 'vue';
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { getStatusBarHeight } from '@/utils/system.js'
import { ApiSetDownload, ApiDetail, ApiSetupScore } from '@/api/apis.js'

const maskState = ref(true)
// 控制信息弹窗的显示与隐藏
const infoPopup = ref(null)
// 控制分数弹窗的显示与隐藏
const scorePop = ref(null)
// 存储用户分数
const userScore = ref(0)
// 存储图片列表
const classList = ref([])
// 存储当前用户ID
const currentID = ref()
// 存储当前图片索引
const currentIndex = ref(0)
// 存储懒加载的图片
const lazyImg = ref([])
// 存储图片信息
const imgInfo = ref(null)

const isSocre = ref(false)

// 实现图片懒加载效果,防止造成浪费
const lazyLoad = () => {
	lazyImg.value.push(
		currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1,
		currentIndex.value,
		currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1)
}
onLoad(async (options) => {
	currentID.value = options.id
	if (options.type == 'share') {
		let res = await ApiDetail({ id: currentID.value })
		classList.value = res.data.map(item => {
			return {
				...item,
				picurl: item.smallPicurl.replace("_small.webp", ".jpg")
			}
		})
	} 

	currentIndex.value = classList.value.findIndex(item => item._id == currentID.value)
	imgInfo.value = classList.value[currentIndex.value]
	// 将当前索引的前一张和后一张都 添加到列表中
	lazyLoad()
	// 获取当前图片的信息
})
// 获取本地存储的列表
// 此处不能使用 onMounted onLoad 的执行时机要早于 onMounted 
// xxx onMounted(()=>{}) xxx
classList.value = uni.getStorageSync('classList') || []
classList.value = classList.value.map((item) => {
	return {
		...item,
		picurl: item.smallPicurl.replace('_small.webp', '.jpg')
	}
})
const currentChange = (e) => {
	currentIndex.value = e.detail.current
	lazyLoad()
	imgInfo.value = classList.value[currentIndex.value]

}
// 控制遮罩层的显示与隐藏
const maskChange = () => {
	maskState.value = !maskState.value
}
const ClickInfo = () => {
	infoPopup.value.open('bottom')
}
// 关闭弹出层
const closePop = () => {
	infoPopup.value.close()
}

// 评分弹出层
const clickScore = () => {
	if (classList.value[currentIndex.value]?.userScore) {
		isSocre.value = true
		userScore.value = classList.value[currentIndex.value]?.userScore
		console.log(userScore.value);
	}
	scorePop.value.open('center')
}
// 关闭评分弹出层
const closeScorePop = () => {
	scorePop.value.close()
	userScore.value = 0
	isSocre.value = false
}
// 确认评分
const submitScore = async () => {
	uni.showLoading({
		title: '加载中'
	})
	const { classid, _id: wallId } = imgInfo.value
	const res = await ApiSetupScore({ classid, wallId, userScore: userScore.value })
	console.log('res',res)
	uni.hideLoading()
		uni.showToast({
			title: '评分成功',
			icon: 'none'
		})
		// 更新本地存储的列表
		classList.value[currentIndex.value].userScore = userScore.value
		uni.setStorageSync('classList', classList.value)
		closeScorePop()
	
}

// 返回上一页
const goBack = () => {
	uni.navigateBack({
		success: () => {

		},
		fail: () => {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}
	})
}

//下载图片
const download = async () => {
	// #ifdef H5
	uni.showModal({
		content: '长按保存',
		showCancel: false
	})
	// #endif

	// #ifndef H5


	try {
		uni.showLoading({
			title: '下载中',
			mask: true
		})
		const { classid, _id: wallId } = imgInfo.value
		const res = await ApiSetDownload({
			classid,
			wallId
		})
		if (res.errCode != 0) throw res;
		uni.getImageInfo({
			src: imgInfo.value.picurl,
			success: ({ path }) => {
				uni.saveImageToPhotosAlbum({
					filePath: path,
					success: function (res) {
						uni.showToast({
							title: "保存成功，请到相册查看",
							icon: "none"
						})
					},
					fail: err => {
						if (err.errMsg === "saveImageToPhotosAlbum:fail cancel") {
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							})
							return
						}
						uni.showModal({
							title: '提示',
							content: '需要授权保存相册',
							success: res => {
								if (res.confirm) {
									uni.openSetting({
										success: (res) => {
											if (res.authSetting['scope.writePhotosAlbum']) {
												uni.showToast({
													title: "获取授权成功",
													icon: "none"
												})
											} else {
												uni.showToast({
													title: "获取权限失败",
													icon: "none"
												})
											}

										}

									})
								}

							}
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			}
		})
	} catch (err) {

		uni.hideLoading()
	}


	// #endif
}
// 分享给好友
onShareAppMessage((e) => {
	return {
		title: '壁纸,',
		path: "/pages/preview/preview?id=" + currentID.value + "&type=share"

	}
})
// 分享朋友圈
onShareTimeline((e) => {
	return {
		title: '壁纸,',
		query: "id=" + currentID.value + "&type=share"
	}
})

</script>

<style lang="scss">
.preview {
	width: 100%;
	height: 100vh;
	position: relative;

	swiper {
		width: 100%;
		height: 100%;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.mask {
		&>view {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}

		.goBack {
			width: 38px;
			height: 38px;
			background: rgba(0, 0, 0, 0.5);
			left: 30rpx;
			margin-left: 30rpx;
			border-radius: 100px;
			backdrop-filter: blur(10px);
			border: 1px solid rgba(255, 255, 255, 0.3);
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.count {
			top: 10vh;
			background: rgba(0, 0, 0, 0.3);
			padding: 8rpx 28rpx;
			border-radius: 40rpx;
			color: #fff;
			font-size: 28rpx;
		}

		.time {

			font-size: 130rpx;
			top: calc(10vh + 80rpx);
			color: #fff;
			text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			font-weight: 100;
		}

		.date {
			font-size: 34rpx;
			color: #fff;
			top: calc(10vh + 230rpx);
			text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);

		}

		.footer {
			background: rgba(255, 255, 255, 0.8);
			bottom: 10vh;
			display: flex;
			width: 65vw;
			justify-content: space-around;
			border-radius: 60rpx;

			align-items: center;
			box-shadow: 0 2rpx rgba(0, 0, 0, 0.1);
			backdrop-filter: blur(20rpx);

			.box {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 5rpx 10rpx;

				.text {
					font-size: 26rpx;
					color: $text-color2;
				}
			}
		}
	}

	.popHeader {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title {
			color: $text-color2;
			font-size: 26rpx;
		}

		.close {
			padding: 6rpx;
		}
	}

	.infoPopup {
		background: #fff;
		padding: 30rpx;
		border-radius: 30rpx 30rpx 0 0;
		overflow: hidden;



		scroll-view {
			max-height: 60vh;

			.content {
				.row {
					display: flex;
					padding: 16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;

					.label {
						color: $text-color3 ;
						width: 140rpx;
						text-align: right;
						font-size: 30rpx;
						margin-right: 10rpx;

						.value {
							flex: 1;
							width: 0;
						}

					}

					.roteBox {
						display: flex;
						align-items: center;
						justify-content: center;

						.score {
							font-size: 26rpx;
							color: $text-color2;
							padding-left: 20rpx;
						}
					}

					.tabs {
						display: flex;
						flex-wrap: wrap;

						.tab {
							border: 1px solid $base-theme-color;
							color: $base-theme-color ;
							font-size: 22rpx;
							padding: 10rpx 30rpx;
							border-radius: 40rpx;
							line-height: 1em;
							margin: 0 10rpx 10rpx 0;
						}

					}
				}

				.class {
					color: $base-theme-color ;
				}
			}

			.copyright {
				font-size: 28rpx;
				padding: 20rpx;
				background: #f6f6f6;
				color: #666;
				border-radius: 10rpx;
				margin: 20rpx 0;
				line-height: 1.6em;
			}
		}
	}

	.scorePop {
		background: #fff;
		padding: 30rpx;
		width: 70vw;
		border-radius: 30rpx;

		.content {
			padding: 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			.text {
				color: #ffca3e;
				padding-left: 10rpx;
				width: 80rpx;
				line-height: 1em;
				text-align: center;
			}
		}

		.footer {
			display: flex;
			align-items: center;
			padding: 10rpx 0;
		}
	}
}
</style>